package com.srpingde.hhh;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.springde.hhh.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.srpingde.hhh.adapter.HHHFenLeiAdapter;
import com.srpingde.hhh.application.HhhApp;
import com.srpingde.hhh.application.HHHDataManage;
import com.srpingde.hhh.bean.MeiTuCollection;
import com.srpingde.hhh.bean.MeiTuCollectionData;
import com.srpingde.hhh.bean.MeiWen;
import com.srpingde.hhh.bean.MeiWenDataBean;
import com.srpingde.hhh.bean.MeiWenShouCangBean;
import com.srpingde.hhh.bean.Pcollection;
import com.srpingde.hhh.bean.PcollectionData;
import com.srpingde.hhh.http.AsyncHttpResponseHandler;
import com.srpingde.hhh.jiekou.HHHIml;
import com.srpingde.hhh.jiekou.HHHInterface;
//这边要跳到商品详情里面//这个类里面的数据的bean要根据你返回的数据重新定义一下
public class MyCollectionsActivity extends Activity {
	String type_tv = null;
	TextView top_title_tv;
	GridView my_collection_gridview;
	ListView my_collection_lv;
	/*ArrayList<WeiQuTianDiMeiTuBean> list;
	List<WeiQuFenLeiBean> WeiQuFenLeiBean;
	ArrayList<ShopCangShangPinDataBean> res;
	ArrayList<WeiQuFenLeiBean> meitures;
	ArrayList<WeiQuFenLeiBean> wenzis;*/
	ImageView back;
	Pcollection pcollection;
	MeiTuCollection cangShangPinBean;
	MeiWen bean;
	List<Map<String, String>> list;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_shang_pin_shou_cang);
        layout();
        my_collection_lv = (ListView) findViewById(R.id.my_collection_lv);
        my_collection_gridview = (GridView) findViewById(R.id.my_collection_gridview);
        //res = new ArrayList<ShopCangShangPinDataBean>();
       // meitures = new ArrayList<WeiQuFenLeiBean>();
        //wenzis = new ArrayList<WeiQuFenLeiBean>();
        if(getIntent().getExtras()!=null){
        	type_tv = getIntent().getStringExtra("type");
        	if(type_tv.equals("1")){
        		top_title_tv.setText("收藏商品【长按可以删除】");/////【长按可以删除】
        		my_collection_gridview.setVisibility(View.VISIBLE);
        		getShangPinData(type_tv);
        	}else if(type_tv.equals("2")){
        		top_title_tv.setText("绝世美图");
        		getMeiTuShouCang(type_tv);
        		my_collection_gridview.setVisibility(View.VISIBLE);
        	}
        	else if(type_tv.equals("3")){
        		getData(type_tv);
        		top_title_tv.setText("经典好文");
        	}
        }
        
        my_collection_gridview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if(type_tv.equals("1")){
					//这边要跳到商品详情里面//这个类里面的数据的bean要根据你返回的数据重新定义一下
					Intent in= new Intent(MyCollectionsActivity.this,XiangQingActivity.class);
					in.putExtra("id", pcollection.getRows().get(arg2).getPid());
					startActivity(in);
				}else if(type_tv.equals("2")){
					Intent in = new Intent(MyCollectionsActivity.this,HHHMeiTuXiangQing.class);
					in.putExtra("image", cangShangPinBean.getRows().get(arg2).getUrl());
					in.putExtra("id", cangShangPinBean.getRows().get(arg2).getPid());
					startActivity(in);
				}
			}
		});
        my_collection_lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent in = new Intent(MyCollectionsActivity.this,MeiWenActivity.class);
				in.putExtra("id", "2");
				in.putExtra("pid",  bean.getRows().get(arg2).getPid());
				in.putExtra("title", bean.getRows().get(arg2).getTitle());
				in.putExtra("content", bean.getRows().get(arg2).getContent());
				startActivity(in);
			}
		});
        back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
    }
   public void  getShangPinData(String type){
	   	String url = HHHInterface.httpHeader + "api.php?pagesize=100&tab=favorite&act=data&uid="+HhhApp.getInstance().getUid()+"&type="+type;
   		Log.e("mytag", url);
   		HHHIml weiQuIml = new HHHIml();
   		weiQuIml.getShangPinShouCangHttp(MyCollectionsActivity.this, url, new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content);
						pcollection = HHHDataManage.getInstance().getPcollection();
						my_collection_gridview.setAdapter(new FenLeiListViewAdapter(MyCollectionsActivity.this,pcollection.getRows()));
					}
				});
    }
   public void getMeiTuShouCang(String type){
	   String url = HHHInterface.httpHeader + "api.php?pagesize=100&tab=favorite&act=data&uid="+HhhApp.getInstance().getUid()+"&type="+type;
  		Log.e("mytag", url);
  		HHHIml weiQuIml = new HHHIml();
  		weiQuIml.getMeiTuShouCangHttp(MyCollectionsActivity.this, url, new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String content) {
						super.onSuccess(content);
						Log.e("mytag", content);
						cangShangPinBean = HHHDataManage.getInstance().getMeiTuCollection();
						try {
							JSONObject jsonObject = new JSONObject(content);
							JSONArray array = jsonObject.getJSONArray("rows");
							list=new ArrayList<Map<String,String>>();
							for(int i = 0;i<array.length();i++){
								JSONObject object = array.getJSONObject(i);
								Map<String, String> map= new HashMap<String, String>();
								map.put("pid", object.getString("pid"));
								map.put("spic", object.getString("spic"));
								map.put("bpic", object.getString("bpic"));
								map.put("date", object.getString("date"));
								map.put("desc", object.getString("desc"));
								list.add(map);
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						my_collection_gridview.setAdapter(new MeiTuCollectionAdapter(list,MyCollectionsActivity.this));
					}
				});
   }
    private void getData(String type){
    		String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=data&uid="+HhhApp.getInstance().getUid()+"&type="+type;
        	Log.e("mytag", url);
        	HHHIml weiQuIml = new HHHIml();
        	weiQuIml.getMeiWenShouCang(MyCollectionsActivity.this, url, new AsyncHttpResponseHandler() {
    					@Override
    					public void onSuccess(String content) {
    						super.onSuccess(content);
    						bean = HHHDataManage.getInstance().getMeiWen();
    						my_collection_lv.setAdapter(new ShouCangWeiQuFenLeiAdapter(MyCollectionsActivity.this, bean.getRows()));
    					}
    				});
    }
    private void layout() {
		// 头的高度
		top_title_tv = (TextView) findViewById(R.id.title);
		RelativeLayout.LayoutParams titleLayoutParams = (RelativeLayout.LayoutParams) top_title_tv.getLayoutParams();
		titleLayoutParams.height = HhhApp.getInstance().title_h();
		top_title_tv.setLayoutParams(titleLayoutParams);
		//返回按钮
		back = (ImageView) findViewById(R.id.back);
		RelativeLayout.LayoutParams backLayoutParams = (LayoutParams) back.getLayoutParams();
		backLayoutParams.height = HhhApp.getInstance().title_h();
		back.setLayoutParams(backLayoutParams);
	}
    private void itemLayout(ImageView imageView){
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.mm_fenlei_select);
		int wh = (int) (HhhApp.getInstance().getDisplayHightAndWightPx()[1]/2);
		FrameLayout.LayoutParams layoutParams = (android.widget.FrameLayout.LayoutParams)imageView.getLayoutParams();  
		layoutParams.height = wh;
		layoutParams.width = wh;
		imageView.setLayoutParams(layoutParams);
	}
  class FenLeiListViewAdapter extends BaseAdapter {
    	ArrayList<PcollectionData> res;
		Context context;
		public FenLeiListViewAdapter(Context context,ArrayList<PcollectionData> res) {
			super();
			this.context = context;
			this.res = res;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return res.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			fenLeiHolder holder = null;
			if(arg1 == null){
				holder = new fenLeiHolder();
				arg1 = LayoutInflater.from(context).inflate(R.layout.weiqulistbean, null);
				holder.icon = (ImageView) arg1.findViewById(R.id.fenlei_item_icon);
				holder.delete = (ImageView) arg1.findViewById(R.id.delete);
				arg1.setTag(holder);
			}else{
				holder = (fenLeiHolder) arg1.getTag();
			}
			itemLayout(holder.icon);
			//holder.icon.setBackgroundResource(images[arg0]);
			PcollectionData bean = res.get(arg0);
			holder.delete.setTag( bean.getPid());
			holder.pid = bean.getPid();
			final ImageView kvShow = holder.icon ;
    		ImageLoader.getInstance().loadImage(HHHIml.httpHeader+bean.getUrl(), new SimpleImageLoadingListener(){
    			@Override
    			public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {
    				BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
    				//kvShow.setImageBitmap(bitmap);
    				kvShow.setBackgroundDrawable(bitmapDrawable);
    			}
    		});	
    		// 删除 收藏     
    		holder.delete.setOnClickListener( new OnClickListener() {
				@Override
				public void onClick(View v) {
					String pid = v.getTag().toString() ; 
					String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=del&pid="+pid+"&uid="+HhhApp.getInstance().getUid()+"&type="+type_tv;
			   		Log.e("mytag", url);
			   		new deleteShouCangTask().execute( url , pid);
				}
			});
    		arg1.setOnClickListener( new OnClickListener() {
				@Override
				public void onClick(View v) {
					//这边要跳到商品详情里面//这个类里面的数据的bean要根据你返回的数据重新定义一下
					Intent in= new Intent(MyCollectionsActivity.this,XiangQingActivity.class);
					in.putExtra("id", res.get(arg0).getPid());					
					in.putExtra("hideShoucang", true);
					startActivity(in);
				}
			});
    		arg1.setOnLongClickListener( new View.OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					final String pid = ((fenLeiHolder)v.getTag()).pid ;
					AlertDialog dialog = new AlertDialog.Builder(
							MyCollectionsActivity.this).create();
					dialog.setTitle("唯趣");
					dialog.setMessage("确定要删除这个收藏吗？");
					dialog.setButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
					dialog.setButton2("删除",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									String url = HHHInterface.httpHeader +"api.php?tab=favorite&act=del&pid="
											+ pid
											+ "&uid="
											+ HhhApp.getInstance().getUid()
											+ "&type=" + type_tv;
									Log.e("mytag", url);
									new deleteShouCangTask().execute(url, pid);
								}
							});
					dialog.show();
					return false;
				}
			});
			return arg1;
		}
		class fenLeiHolder{
			ImageView icon;
			ImageView delete;
			String pid;
		}
	}
  
  class deleteShouCangTask extends AsyncTask<String, Integer, String>{
	@Override
	protected String doInBackground(String... params) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(params[0]);
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if( httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){
				String result = EntityUtils.toString( httpResponse.getEntity() );
				return result;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return "";
	}
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		Toast.makeText(getBaseContext(), "删除收藏成功", Toast.LENGTH_SHORT).show();
		if( type_tv.equals("1") )
    		getShangPinData(type_tv);
		if( type_tv.equals("2") )
    		getMeiTuShouCang(type_tv);
		if( type_tv.equals("3") )
    		getData(type_tv);
	}
  }
  
  class ShouCangWeiQuFenLeiAdapter extends BaseAdapter {
		Context context;
		List<MeiWenShouCangBean> WeiQuFenLeiBean;
		public ShouCangWeiQuFenLeiAdapter(Context context,List<MeiWenShouCangBean> WeiQuFenLeiBean) {
			super();
			this.context = context;
			this.WeiQuFenLeiBean = WeiQuFenLeiBean;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return WeiQuFenLeiBean.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			WeiQuFenLeiHolder holder = null;
			if(convertView == null){
				convertView = LayoutInflater.from(context).inflate(R.layout.weiqufenlei_item, null);
				holder = new WeiQuFenLeiHolder();
				holder.title = (TextView) convertView.findViewById(R.id.biaoti);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				holder.delete = (ImageView) convertView.findViewById(R.id.delete);
				holder.delete.setVisibility( View.GONE );
				convertView.setTag(holder);
			}else{
				holder = (WeiQuFenLeiHolder) convertView.getTag();
			}
			MeiWenShouCangBean bean = WeiQuFenLeiBean.get(position);
			holder.delete.setTag( bean.getPid() );
			holder.pid = bean.getPid();
			holder.title.setText(bean.getTitle()==null?"null":bean.getTitle());
			holder.time.setText(bean.getContent());
			convertView.setOnClickListener( new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent in = new Intent(MyCollectionsActivity.this,MeiWenActivity.class);
					in.putExtra("id", "3");
					in.putExtra("hideShoucang", true);
					in.putExtra("aid",  WeiQuFenLeiBean.get(position).getPid());
					in.putExtra("title", WeiQuFenLeiBean.get(position).getTitle());
					in.putExtra("content", WeiQuFenLeiBean.get(position).getContent());
					startActivity(in);
				}
			});
			convertView.setOnLongClickListener( new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					final String pid = ((WeiQuFenLeiHolder)v.getTag()).pid ;
			   		AlertDialog dialog = new AlertDialog.Builder( MyCollectionsActivity.this ).create();
					dialog.setTitle("唯趣");
					dialog.setMessage("确定要删除这个收藏吗？");
					dialog.setButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
						}
					});
					dialog.setButton2("删除", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=del&pid="+pid+"&uid="+HhhApp.getInstance().getUid()+"&type="+type_tv;
					   		Log.e("mytag", url);
					   		new deleteShouCangTask().execute( url , pid);
						}
					});
					dialog.show();
					return true;
				}
			});
			holder.delete.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					
				}
			});
			return convertView;
		}
		class WeiQuFenLeiHolder{
			TextView title;
			TextView time;
			ImageView delete;
			String pid;
		}
  }
    class MeiTuCollectionAdapter extends BaseAdapter{
    	Context context;
    	List<Map<String, String>> list;
    	public MeiTuCollectionAdapter(List<Map<String, String>> list, Context context) {
    		super();
    		this.list = list;
    		this.context = context;
    	}
    	@Override
    	public int getCount() {
    		// TODO Auto-generated method stub
    		return list.size();
    	}

    	@Override
    	public Object getItem(int position) {
    		// TODO Auto-generated method stub
    		return null;
    	}

    	@Override
    	public long getItemId(int position) {
    		// TODO Auto-generated method stub
    		return 0;
    	}

    	class fenLeiHolder{
			ImageView icon;
			ImageView delete;
			String pid;
		}
    	
    	@Override
    	public View getView(final int position, View convertView, ViewGroup parent) {
    		
    		fenLeiHolder holder = null;
			if(convertView == null){
				holder = new fenLeiHolder();
				convertView = LayoutInflater.from(context).inflate(R.layout.weiqulistbean, null);
				holder.icon = (ImageView) convertView.findViewById(R.id.fenlei_item_icon);
				holder.delete = (ImageView) convertView.findViewById(R.id.delete);
				convertView.setTag(holder);
			}else{
				holder = (fenLeiHolder) convertView.getTag();
			}
			itemLayout(holder.icon);
			//holder.icon.setBackgroundResource(images[arg0]); 
			Map<String, String> bean = list.get(position); 
			holder.delete.setTag( bean.get("pid")); 
			holder.pid = bean.get("pid") ; 
			final ImageView kvShow = holder.icon ; 
    		ImageLoader.getInstance().loadImage(HHHIml.httpHeader+bean.get("spic"), new SimpleImageLoadingListener(){
    			@Override
    			public void onLoadingComplete(String imageUri, View view, Bitmap bitmap) {
    				BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
    				kvShow.setBackgroundDrawable(bitmapDrawable);
    			}
    		});	
    		// 删除 收藏     
    		holder.delete.setOnClickListener( new OnClickListener() {
				@Override
				public void onClick(View v) {
					String pid = ((fenLeiHolder)v.getTag()).pid; 
					String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=del&pid="+pid+"&uid="+HhhApp.getInstance().getUid()+"&type="+type_tv;
			   		Log.e("mytag", url);
			   		new deleteShouCangTask().execute( url , pid);
				}
			});
    		convertView.setOnClickListener( new OnClickListener() {
				@Override
				public void onClick(View v) {
					////////////////////////////////////////////////////////////////////////////////
					///读取小图数据，点击大图的时候没有相关大图链接数据
					////////////////////////////////////////////////////////////////////////////////
					Intent in = new Intent(MyCollectionsActivity.this,HHHMeiTuXiangQing.class);
					in.putExtra("image", list.get(position).get("bpic"));//gouWuChe.getRows().get(arg2).getBpic());//
					in.putExtra("id", list.get(position).get("pid"));
					in.putExtra("name", list.get(position).get("desc"));
					in.putExtra("hideShoucang", true);
					startActivity(in);
				}
			});
    		convertView.setOnLongClickListener( new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					final String pid = ((fenLeiHolder)v.getTag()).pid;
					AlertDialog dialog = new AlertDialog.Builder(
							MyCollectionsActivity.this).create();
					dialog.setTitle("唯趣");
					dialog.setMessage("确定要删除这个收藏吗？");
					dialog.setButton("取消",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
					dialog.setButton2("删除",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									String url = HHHInterface.httpHeader + "api.php?tab=favorite&act=del&pid="+pid+"&uid="+HhhApp.getInstance().getUid()+"&type="+type_tv;
									Log.e("mytag", url);
									new deleteShouCangTask().execute(url, pid);
								}
							});
					dialog.show();
					return false;
				}
			});
			return convertView;
    	}
    }	
}
